package com.sgcc.nfc.lock.core.network

sealed class NetworkResult<out T> {
    data class Success<T>(val data: T) : NetworkResult<T>()
    data class Error(val code: Int?, val message: String?, val cause: Throwable? = null) : NetworkResult<Nothing>()
    data object Loading : NetworkResult<Nothing>()
}

suspend inline fun <T> safeApiCall(crossinline block: suspend () -> ApiResponse<T>): NetworkResult<T> {
    return try {
        val response = block()
        if (response.isSuccess && response.data != null) {
            NetworkResult.Success(response.data)
        } else {
            NetworkResult.Error(response.code, response.message)
        }
    } catch (t: Throwable) {
        NetworkResult.Error(null, t.localizedMessage, t)
    }
}

suspend inline fun safeApiCallVoid(crossinline block: suspend () -> ApiResponse<Unit>): NetworkResult<Unit> {
    return try {
        val response = block()
        if (response.isSuccess) {
            NetworkResult.Success(Unit)
        } else {
            NetworkResult.Error(response.code, response.message)
        }
    } catch (t: Throwable) {
        NetworkResult.Error(null, t.localizedMessage, t)
    }
}
